import { Ref, ref } from 'vue'
import { storeToRefs } from 'pinia'
import searchStore, { KeyWord, initKeyWordVal } from '@/piniastore/search/index'
import bookStore, { Operate } from '@/piniastore/book'
import { ctgyStore } from '@/piniastore/ctgy/index'
import router from '@/router'

class SearchService {
  static searchService: SearchService = new SearchService()
  static isOpenAutoComplete: Ref<boolean> = ref(false)
  static store = searchStore()
  static storeRefs = storeToRefs(SearchService.store)
  static bkStore = bookStore()
  static cStore = ctgyStore()

  static init() {
    if (!SearchService.store.getHistoryKeyWordObjList) {
      SearchService.store.searchDecovery()
    }
    if (!SearchService.store.getHistoryKeywordList) {
      SearchService.store.getHistoryList()
    }
  }
  static searchKeyWords = debounce(async (event) => {
    SearchService.store.storeKeyWord(event)
    if (SearchService.getKeyWordVal() == '') {
      SearchService.showOrCloseAutoComplete(false)
      return
    }
    SearchService.store.searchKeywords(event)
    SearchService.showOrCloseAutoComplete(true)
  })
  static showOrCloseAutoComplete(flag: boolean) {
    SearchService.isOpenAutoComplete.value = flag
  }
  static getKeyWordVal() {
    const keyWord = SearchService.store.keyWord
    return keyWord
  }
  static closeKeyWords() {
    if (!SearchService.getKeyWordVal()) {
      SearchService.store.storeKeyWord(initKeyWordVal)
    }
    SearchService.showOrCloseAutoComplete(false)
  }
  static resetKeyWords() {
    if (SearchService.getKeyWordVal() === initKeyWordVal) {
      SearchService.store.storeKeyWord('')
    } else {
      SearchService.showOrCloseAutoComplete(true)
    }
  }
  static async searchBookByKey(keyword: any) {
    await SearchService.store.addOrUpdateHistoryKeyword(keyword)
    SearchService.showOrCloseAutoComplete(false)
    SearchService.bkStore.storeOperate(Operate.AUTOCOMPKEYWORD)
    SearchService.store.storeAutoCompKeyword(keyword)
    SearchService.cStore.storeThirdCtgy({
      thirdctgyid: 0,
      thirdctgyname: '全部',
      secctgyid: 0,
    })
    router.push('/books/0')
  }
  static async deleteHistoryKeyWord(id: number) {
    await SearchService.store.deleteHistoryKeyWord(id)
  }
}

type CommonFunType = (...args: any) => any
function debounce<T extends CommonFunType>(fn: T, wait: number = 200) {
  let timer: any = 0
  return function (...args: Parameters<T>) {
    if (timer) window.clearTimeout(timer)
    timer = window.setTimeout(() => {
      fn(...args)
      timer = 0
    }, wait)
  }
}

export default SearchService
